package com.xinyuan.servlet;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xinyuan.entity.ResultInfo;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

/**
 * @Classname ${NAME}
 * @Description TODO
 * @Date 2020/5/30 22:16
 * @Created by zfl
 */
@WebServlet(name = "DownloadMotpOne" , urlPatterns = "/downloadMTOPOne")
public class DownloadMtopOne extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.addHeader("Access-Control-Allow-Origin","*");
        String fileID = request.getParameter("id");
        System.out.println(fileID);
        String filePath = "C:\\upload\\" + fileID + "\\MTOPONE.xlsx";
        String fileName;
        File file = new File(filePath);
        if(!file.exists()) {
            filePath = "C:\\upload\\" + fileID + "\\MTOPONE.xls";
            fileName = "MTOPONE.xls";
        }else {
            fileName = "MTOPONE.xlsx";
        }
        File file1 = new File(filePath);
        if(file1.exists()) {
            //设置强制下载不打开
            response.setContentType("application/force-download");
            response.addHeader("Content-Disposition","attachment;fileName = " + fileName);
            byte[] buffer = new byte[1024 * 8];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            try {
                fis = new FileInputStream(file1);
                bis = new BufferedInputStream(fis);
                OutputStream os = response.getOutputStream();
                int len;
                while ((len = bis.read(buffer)) != -1) {
                    os.write(buffer,0,len);
                }
                System.out.println("下载成功！");
            } catch (IOException e) {
                System.out.println("下载失败！");
            } finally {
                if (bis != null) {
                    bis.close();
                }
                if (fis != null) {
                    fis.close();
                }
            }
        }else {
            ResultInfo info = new ResultInfo();
            info.setMsg("找不到文件，请先上传文件！");
            info.setErrorCode(1);
            info.setData(null);
            ObjectMapper mapper = new ObjectMapper();
            response.setContentType("application/json;charset=utf-8");
            mapper.writeValue(response.getOutputStream(),info);
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
